package org.ezplatform.office.rd.archives.service;

import org.ezplatform.office.rd.common.SM3Util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpPost {
    private final String USER_AGENT = "Mozilla/5.0";
    public static final Logger log = LoggerFactory.getLogger(HttpPost.class);

    public static void main(String[] args) throws Exception {
        File file=new File("D:\\Documents\\225\\ee7125f4c2f3470e8638758ba2276e97.zip");
        String sm3= SM3Util.getFileSM3String(file);
        log.error("sm3======={}", sm3);
        HttpPost http = new HttpPost();
        http.sendPost("http://172.24.3.5:8112/botong/dataReceive",sm3,"收文","档案对接数据推送测试第二条","1a9ad510e0994261bbefdb0fc608dc49","00000");
    }

    // HTTP Post请求
    public boolean sendPost(String url,String digitalAbstract,String type,String title,String govid,String qzh)  {
        boolean isOK=false;
//        String url = "http://172.24.3.5:8112/botong/dataReceive";
        OutputStreamWriter out = null;
        BufferedReader br = null;
        String result = "";
        
        log.error("=== HTTP请求开始 ===");
        log.error("请求URL: {}", url);
        log.error("digitalAbstract: {}", digitalAbstract);
        log.error("type: {}", type);
        log.error("title: {}", title);
        log.error("govid: {}", govid);
        log.error("qzh: {}", qzh);
        
        try {
            URL obj = new URL(url);
            String boundary="----WebKitFormBoundary7MA4YWxkTrZu0gW";
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            // 添加请求头
            con.setConnectTimeout(5000);
            con.setReadTimeout(30000);
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestMethod("POST");
            con.setRequestProperty("Connection", "Keep-Alive");
            con.setRequestProperty("User-Agent", "Mozilla/5.0");
            con.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);

            StringBuffer strBuf=new StringBuffer();
            String hy="hy";
            strBuf.append("--").append(boundary).append("\r\n");
            strBuf.append("Content-Disposition: form-data;name=\"systemCode\"\r\n\r\n" + hy + "\r\n");

            strBuf.append("--").append(boundary).append("\r\n");
//        String digitalAbstract="be533520e31a0565a5ee1e95c12020848ca9663a384e85e5c45419fa9cfe6c55";
            strBuf.append("Content-Disposition: form-data;name=\"digitalAbstract\"\r\n\r\n" + digitalAbstract + "\r\n");

            strBuf.append("--").append(boundary).append("\r\n");
//        String type="收文";
            strBuf.append("Content-Disposition: form-data;name=\"type\"\r\n\r\n" + type + "\r\n");

            strBuf.append("--").append(boundary).append("\r\n");
//        String govid="ed0ca56869c340df8b3cea25c2445305";
            strBuf.append("Content-Disposition: form-data;name=\"govid\"\r\n\r\n" + govid + "\r\n");

            strBuf.append("--").append(boundary).append("\r\n");
//        String title="测试推送收文222";
            strBuf.append("Content-Disposition: form-data;name=\"title\"\r\n\r\n" + title + "\r\n");


            strBuf.append("--").append(boundary).append("\r\n");
//        String qzh="00000";
            strBuf.append("Content-Disposition: form-data;name=\"qzh\"\r\n\r\n" + qzh + "\r\n");

            strBuf.append("--").append(boundary).append("--");

            // 发送Post请求
            con.setDoOutput(true);

            //获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
            //发送请求参数即数据
            out.write(strBuf.toString());
            //flush输出流的缓冲
            out.flush();

            //获取URLConnection对象对应的输入流
            InputStream is = con.getInputStream();
            //构造一个字符流缓存
            br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str = br.readLine()) != null){
                result += str;
            }
            log.error("=== HTTP响应结果 ===");
            log.error("发送的请求URL：{}", url);
            log.error("响应内容：{}", result);
            
            if(result.contains("200")){
                isOK=true;
                log.error("=== HTTP请求成功 ===");
                log.error("响应状态：成功 (包含200状态码)");
            } else {
                log.error("=== HTTP请求失败 ===");
                log.error("响应状态：失败 (未包含200状态码)");
                if(result.contains("500")) {
                    log.error("错误类型：服务器内部错误 (500)");
                }
                if(result.contains("重复推送")) {
                    log.error("错误原因：文件重复推送");
                }
            }
            //关闭流
            is.close();
            //断开连接，disconnect是在底层tcp socket链接空闲时才切断，如果正在被其他线程使用就不切断。
            con.disconnect();
            /**
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());

            wr.writeBytes(strBuf.toString());
            wr.flush();
            wr.close();

            int responseCode = con.getResponseCode();
            System.out.println("发送的请求URL：" + url);
            System.out.println("响应代码：" + responseCode);

            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 打印响应结果
            System.out.println("响应结果：" + response.toString());
            if(response.toString().contains("200")){
                return true;
            }
             */
        } catch (Exception e) {
            log.error("=== HTTP请求异常 ===");
            log.error("异常类型：{}", e.getClass().getSimpleName());
            log.error("异常信息：{}", e.getMessage());
            log.error("请求URL：{}", url);
            log.error("异常堆栈：", e);
        }finally {
            try {
                if (out != null){
                    out.close();
                }
                if (br != null){
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return isOK;
    }

}
